using System;
using System.Threading;

using Azure.Domain.Messages;
using Azure.Domain.Services;
using Azure.Infrastructure;

namespace Azure.Domain.Processors
{
    public class CommentProcessor : BaseProcessor
    {
        private readonly IQueue<NewCommentMessage> _queue;
        private readonly Func<ICommentService> _getCommentService;
        private AutoResetEvent _waitHandle = new AutoResetEvent(false);
        private bool _stop = false;
        private readonly TimeSpan _queueWaitTime;

        public CommentProcessor(IQueue<NewCommentMessage> queue, TimeSpan queueWaitTime, Func<ICommentService> getCommentService)
        {
            _queue = queue;
            _queueWaitTime = queueWaitTime;
            _getCommentService = getCommentService;
        }

        protected override void OnStart()
        {
            while (!_stop)
            {
                var message = _queue.Dequeue(_queueWaitTime);
                var service = _getCommentService();
                service.Process(message.Body);
            }

            _waitHandle.Set();
        }

        protected override void OnStop()
        {
            _stop = true;
            _waitHandle.WaitOne();
        }

        protected override void Dispose(bool disposing)
        {
            if (_waitHandle != null)
            {
                _waitHandle.Close();
                ((IDisposable) _waitHandle).Dispose();
                _waitHandle = null;
            }

            base.Dispose(disposing);
        }
    }
}